<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div ref="ele">
        <!-- 搜索 -->
        <label class="el-form-item-label">订单号</label>
        <el-input v-model="query.orderNo" placeholder="订单号" clearable style="width: 155px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--<label class="el-form-item-label">煤矿名称</label>
        <el-select v-model="query.mineMouthId" filterable placeholder="全部" clearable @change="crud.toQuery" style="width: 155px;" class="filter-item">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.mineMouthName"
            :value="item.id">
          </el-option>
        </el-select>-->
        <label class="el-form-item-label">结算人电话</label>
        <el-input v-model="query.applyUserPhone" clearable maxlength="11" placeholder="结算人电话" style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">结算单号</label>
        <el-input v-model="query.settlementNo" placeholder="结算号" clearable style="width: 135px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">申请时间</label>
        <date-range-picker v-model="query.applyTime" class="date-item" />
        <label v-if="this.activeName === '2'" class="el-form-item-label">结算时间</label>
        <date-range-picker v-if="this.activeName === '2'" v-model="query.settleTime" class="date-item" />
        <rrOperation :crud="crud" />
      </div>
      <!--<crudOperation :permission="permission"></crudOperation>-->
    </div>
    <el-tabs v-model="activeName" style="padding: 0" type="card" @tab-click="handleClick">
      <el-tab-pane label="全部" name="null"></el-tab-pane>
      <el-tab-pane label="待结算" name="1" />
      <el-tab-pane label="已结算" name="3" />
      <el-tab-pane label="退回" name="2" />

      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :height="tableHeight"
        border
        :data="crud.data"
        style="width: 100%;"
        :summary-method="getCommSummaries({customer: crud.totalObject, titleIndex: 0})"
        :show-summary="false"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="60" align="center" />
        <el-table-column prop="settlementNo" width="175" label="结算单号" align="center" show-overflow-tooltip />
        <el-table-column prop="orderNo" width="175" label="订单号" align="center" show-overflow-tooltip />
        <el-table-column prop="merchantName" width="175" label="运输公司" align="center" show-overflow-tooltip />
        <el-table-column prop="phone" width="110" label="申请人电话" align="center" show-overflow-tooltip />
        <el-table-column prop="allotNum" width="110" label="分配数量（吨）" align="center" show-overflow-tooltip />
        <el-table-column prop="mineHairNum" width="110" label="实发数量（吨）" align="center" show-overflow-tooltip />
        <el-table-column prop="arrivalNum" width="110" label="到货数量（吨）" align="center" show-overflow-tooltip />
        <el-table-column prop="takePrice" width="110" label="接单价格(元/吨)" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="search-text1">{{ scope.row.takePrice | nullFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="issuePrice" width="110" label="发布价格(元/吨)" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="search-text1">{{ scope.row.issuePrice | nullFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalPrice" width="110" label="总运费(元/吨)" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="search-text1">{{ scope.row.totalPrice | nullFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="profit" width="110" label="盈利(元/吨)" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="search-text1">{{ scope.row.profit | nullFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" width="100" label="状态" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 3 ? 'success' : scope.row.status === 1 ? 'primary' : 'warning'">
              {{ scope.row.status === 1 ? "待结算" :
                scope.row.status === 3 ? "已结算" :
                scope.row.status === 2 ? "已拒绝" : "-" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" width="150" label="申请时间" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ parseTime(scope.row.applyTime,'{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
        <el-table-column prop="rejectTime" width="150" label="驳回时间" v-if="activeName === '2' || activeName === 'null'" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ parseTime(scope.row.rejectTime,'{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
        <el-table-column prop="casue" width="100" label="退回原因" v-if="activeName === '2' || activeName === 'null'" align="center" show-overflow-tooltip />
        <el-table-column prop="settleTime" width="150" v-if="activeName === '3' || activeName === 'null'" label="结算时间" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ parseTime(scope.row.settleTime,'{y}-{m}-{d} {h}:{i}') }}
          </template>
        </el-table-column>
        <el-table-column v-if="activeName !== '2'" label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 1"
              size="mini"
              type="primary"
              @click="refuseBtnClick(scope.row)"
            >结算</el-button>
            <el-button
              v-if="scope.row.status === 2"
              size="mini"
              type="info"
              @click="createBtnClick(scope.row)"
            >结算详情</el-button>
          </template>
        </el-table-column>
      <!--<el-table-column label="订单流程" align="center" width="95" fixed="right" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top" width="500">
            <el-table :data="scope.row.merchantOrderRecords">
              <el-table-column width="100" property="username" label="操作人账号"></el-table-column>
              <el-table-column width="90" property="orderStatus" label="操作状态">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.orderStatus === 1 ? 'success' : 'warning'">
                    {{ scope.row.orderStatus | orderStatusFilter }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column width="120" property="operationTime" show-overflow-tooltip label="操作时间">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.operationTime)}}</span>
                </template>
              </el-table-column>
              <el-table-column property="remark" show-overflow-tooltip label="操作备注"></el-table-column>
            </el-table>
            <a slot="reference" class="name-wrapper">
              <el-tag size="medium">操作流程</el-tag>
            </a>
          </el-popover>
        </template>
      </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination />
    </el-tabs>
    <div class="panel">
      <form-panel v-if="showFormPanel" :show-form-panel.sync="showFormPanel" :item="selectedItem" @refreshList="crud.toQuery" />
    </div>
    <el-dialog
      title="结算"
      class="tiny-mce-dialog"
      :visible.sync="dialogVisible"
      width="400px"
    >
      <el-form ref="causeValue" :model="causeValue" :rules="causeValues" size="small" label-width="80px">
        <el-card class="box-card">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="结算备注" prop="casue" label-width="60px">
                <el-input
                  v-model="causeValue.casue"
                  clearable
                  type="textarea"
                  placeholder="请输入结算备注"
                  :autosize="{ minRows: 6, maxRows: 10}"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-loading="fullscreenLoading" type="info" @click="dialogVisible = false">取消</el-button>
        <el-button v-loading="fullscreenLoading" type="danger" @click="save(false)">驳回</el-button>
        <el-button v-loading="fullscreenLoading" type="success" @click="save(true)">确认结算</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, { crud, header, presenter } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker/index'
import Form from './form'

export default {
  name: 'MerchantFreightSettle',
  components: { pagination, rrOperation, DateRangePicker, 'form-panel': Form },
  mixins: [presenter(), header(), crud()],
  cruds() {
    return CRUD({ title: '货运申请结算管理', url: 'api/transportSettle/list', query: { status: 1 }, idField: 'applyTime', sort: 'transportSettlementId,desc', crudMethod: { }})
  },
  data() {
    return {
      activeName: '1',
      showFormPanel: false,
      dialogVisible: false,
      fullscreenLoading: false,
      causeValue: {},
      transportSettlementId: null,
      height: this.getTableHeight({}),
      tableHeight: this.height,
      echodisplaylist: [],
      selectedItem: {},
      dialogFormVisible: false,
      options: [],
      merchant: [],
      coalType: [
        { name: '全部', ecode: null, id: null }
      ],
      coalName: [],
      coalData: null,
      coalValueData: {},
      status: [
        { key: '全部', value: null },
        { key: '已下单', value: 1 },
        { key: '用户取消', value: 2 },
        { key: '商户确认', value: 3 },
        { key: '商户拒绝', value: 4 },
        { key: '关闭（24小时）', value: 5 },
        { key: '已支付', value: 6 },
        { key: '商户确认', value: 7 }
      ],
      priceUnit: '',
      baseCatesValue: [],
      forms: {
        coalInfos: []
      },
      /* causeValues: {
        casue: [
          { required: true, message: '请输入驳回原因', trigger: 'blur' }
        ]
      },*/
      permission: {
        add: ['admin', 'coalProducts:add'],
        edit: ['admin', 'coalProducts:edit'],
        del: ['admin', 'coalProducts:del']
      }
    }
  },

  created() {
    this.crud.optShow = {
      reset: true,
      add: false,
      edit: false,
      del: false,
      download: false
    }
  },
  mounted: function() {
    this.tableHeight = this.height - this.$refs.ele.clientHeight - 15
    this.getCategory()
    this.search()
  },
  methods: {
    createBtnClick(value) {
      this.selectedItem = value
      this.showFormPanel = true
    },
    handleClick() {
      const self = this
      self.crud.query.status = self.activeName === 'null' ? null : self.activeName
      self.crud.toQuery()
    },
    save(val) {
      const self = this
      if (!val && !self.causeValue.casue){
        self.$message({
          message: '请输入驳回原因',
          type: 'error'
        })
        return
      }
      const pram = {
        id: self.transportSettlementId,
        msg: self.causeValue.casue,
        falg: val
      }
      self.$http.post('/api/transportSettle/approve', pram)
        .then(function(res) {
          self.dialogVisible = false
          self.causeValue = {}
          self.crud.toQuery()
        }).catch(function(error) {
          self.fullscreenLoading = false
          console.log(error)
        })
    },
    /* createBtnClick(value) {
      let self = this
      self.$confirm('确定要确认该订单吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let pram = {
          id: value.freightSettlementId,
          falg: true
        }
        self.$http.put('/api/supplyOrder/operation', pram)
          .then(function (res) {
            self.fullscreenLoading = false
            self.dialogVisible = false
            if (res.ok){
              self.$message({
                type: 'success',
                message: '确认成功!'
              })
              self.crud.toQuery()
            }
          }).catch(function (error) {
            self.fullscreenLoading = false
            console.log(error)
        })
      }).catch(() => {
        /!*this.$message({
          type: 'info',
          message: '已取消确认'
        });*!/
      })
    },*/
    refuseBtnClick(value) {
      this.transportSettlementId = value.transportSettlementId
      this.dialogVisible = true
    },
    getCurrentMonthFirst() {
      var date = new Date()
      date.setDate(1)
      date.setHours(0)
      date.setSeconds(0)
      date.setMinutes(0)
      return date
    },
    getCommSummaries({ column, customer, title = '合计', titleIndex }) {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
      return function(param) {
        const sums = []
        const { columns, data } = param
        columns.forEach((columnItem, index) => {
          if ((titleIndex === undefined && columnItem.type === 'index') || index === titleIndex) {
            sums[index] = title
          } else if (customer) {
            sums[index] = customer[columnItem.property] === null || customer[columnItem.property] === undefined || customer[columnItem.property] === '' ? '-' : customer[columnItem.property]
          } else {
            const sumList = []
            column.forEach((e) => {
              if (e.toString().includes('-')) {
                for (let i = Number(e.split('-')[0]); i <= Number(e.split('-')[1]); i++) {
                  sumList.push(i)
                }
              } else {
                sumList.push(Number(e))
              }
            })
            if (sumList.includes(index)) {
              const values = data.map(e => Number(e[columnItem.property]))
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr)
                  if (!isNaN(value)) {
                    return prev + curr
                  } else {
                    return prev
                  }
                }, 0)
                sums[index] += ''
              } else {
                sums[index] = '-'
              }
            }
          }
        })
        return sums
      }
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields()
    },
    objectKey(key, value) {
      const keyValue = {}
      keyValue[key] = value
      return key
    },
    search() {
      const self = this
      self.$http.get('/api/mineMouth/getMineMouth').then(function(value) {
        self.options = value
      })
      self.$http.get('/api/systemController/getMerchant').then(function(value) {
        if (value.ok) {
          self.merchant = value.data
        }
      })
    },
    getCategory() {
      const self = this
      self.$http.get("/api/coalCategory/query").then(function(value) {
        self.coalType = self.coalType.concat(value)
      })
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }
  }
}
</script>

<style scoped>

</style>
